package com.tianyang.yukuaifu.business.main.view;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;

import com.google.zxing.Result;
import com.tianyang.yukuaifu.R;
import com.tianyang.yukuaifu.base.ICommonProvider;
import com.tianyang.yukuaifu.base.PermissionActivity;
import com.tianyang.yukuaifu.business.main.contract.MainConfig;
import com.tianyang.yukuaifu.common.interfaces.CommonConfig;
import com.tianyang.yukuaifu.jump.zxscan.CaptureCallback;
import com.tianyang.yukuaifu.jump.zxscan.camera.CameraManager;
import com.tianyang.yukuaifu.jump.zxscan.decode.DecodeThread;
import com.tianyang.yukuaifu.jump.zxscan.utils.BeepManager;
import com.tianyang.yukuaifu.jump.zxscan.utils.CaptureActivityHandler;
import com.tianyang.yukuaifu.jump.zxscan.utils.InactivityTimer;
import com.tianyang.yukuaifu.jump.zxscan.utils.Utils;
import com.tianyang.yukuaifu.utils.AlbumUtil;
import com.tianyang.yukuaifu.utils.PublicProviderUtil;
import com.tianyang.yukuaifu.utils.ScreenUtil;
import com.tianyang.yukuaifu.utils.ToastUtil;
import com.tianyang.yukuaifu.utils.permissions.PermissionsConstant;
import com.tianyang.yukuaifu.utils.permissions.PermissionsMgr;

import java.io.IOException;
import java.util.List;

/**
 * description:扫一扫
 */
public class CaptureActivity extends PermissionActivity implements CaptureCallback, SurfaceHolder.Callback {

    private String[] permissions = new String[]{PermissionsConstant.CAMERA};

    private String permission = PermissionsConstant.WRITE_STORAGE;

    private static final String TAG = "CaptureActivity";

    private SurfaceView scanPreview; // SurfaceView控件
    private RelativeLayout scanContainer; // 布局容器
    private RelativeLayout scanCropView; // 布局中的扫描框
    private ImageView lightIv;

    private ObjectAnimator objectAnimator; // 属性动画
    private boolean isPause; // 是否暂停

    private InactivityTimer inactivityTimer; // 计时器
    private BeepManager beepManager; // 蜂鸣器
    private CaptureActivityHandler handler;
    private Rect mCropRect; // 矩形
    private CameraManager cameraManager; // 相机管理类
    private boolean isHasSurface; // SurfaceView控件是否存在，surfaceCreated

    private boolean isCheckLight = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        //隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //隐藏状态栏
        //定义全屏参数
        int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
        //设置当前窗体为全屏显示
        window.setFlags(flag, flag);
        setContentView(R.layout.activity_capture);
        initView();
        initScan();
        initEvent();

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
            if (!PermissionsMgr.getInstance().hasAllPermissions(this, permissions)) {
                requestPermissions(permissions);
            }
        }
    }

    private void initView() {
        scanPreview = findViewById(R.id.capture_preview);
        scanContainer = findViewById(R.id.capture_container);
        scanCropView = findViewById(R.id.capture_crop_view);
        lightIv = findViewById(R.id.lightIv);
    }

    // 扫码初始化
    private void initScan() {
        ImageView scanLine = findViewById(R.id.scan_line);

        // 扫描线性动画(属性动画可暂停)
        float curTranslationY = scanLine.getTranslationY();
        objectAnimator = ObjectAnimator.ofFloat(scanLine, "translationY",
                curTranslationY, ScreenUtil.dp2px(this, 270));
        // 动画持续的时间
        objectAnimator.setDuration(4000);
        // 线性动画 Interpolator 匀速
        objectAnimator.setInterpolator(new LinearInterpolator());
        // 动画重复次数
        objectAnimator.setRepeatCount(ObjectAnimator.INFINITE);
        // 动画如何重复，从下到上，还是重新开始从上到下
        objectAnimator.setRepeatMode(ValueAnimator.RESTART);
    }

    private void initEvent() {
        lightIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCheckLight) {
                    isCheckLight = false;
                    Utils.closeFlashlight();
                    lightIv.setImageResource(R.drawable.ic_scan_light);
                } else {
                    isCheckLight = true;
                    Utils.openFlashlight(cameraManager);
                    lightIv.setImageResource(R.drawable.ic_scan_light_close);
                }
            }
        });

        // 打开相册
        findViewById(R.id.ll_album).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
                    if (!PermissionsMgr.getInstance().hasPermission(CaptureActivity.this, permission)) {
                        requestPermissions(permission);
                        return;
                    }
                }
                AlbumUtil.openAlbum(CaptureActivity.this, CommonConfig.REQUESTCODE_CAPTURE_PICKER);
            }
        });

        findViewById(R.id.finishIv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        startScan();
    }

    @Override
    protected void onPause() {
        pauseScan();
        super.onPause();
    }

    // 开始扫描
    private void startScan() {
        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);

        if (isPause) {
            // 如果是暂停，扫描动画应该要暂停
            objectAnimator.resume();
            isPause = false;
        } else {
            // 开始扫描动画
            objectAnimator.start();
        }

        // 初始化相机管理
        cameraManager = new CameraManager(this);
        handler = null; // 重置handler
        if (isHasSurface) {
            initCamera(scanPreview.getHolder());
        } else {
            // 等待surfaceCreated来初始化相机
            scanPreview.getHolder().addCallback(this);
        }
        // 开启计时器
        if (inactivityTimer != null) {
            inactivityTimer.onResume();
        }
    }

    // 暂停扫描
    private void pauseScan() {
        if (handler != null) {
            // handler退出同步并置空
            handler.quitSynchronously();
            handler = null;
        }
        // 计时器的暂停
        if (inactivityTimer != null) {
            inactivityTimer.onPause();
        }
        // 关闭蜂鸣器
        beepManager.close();
        // 关闭相机管理器驱动
        cameraManager.closeDriver();
        if (!isHasSurface) {
            // remove等待
            scanPreview.getHolder().removeCallback(this);
        }
        // 动画暂停
        objectAnimator.pause();
        isPause = true;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (holder == null) {
            Log.e(TAG, "surfaceCreated: SurfaceHolder is null");
            return;
        }

        if (!isHasSurface) {
            isHasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isHasSurface = false;
    }

    // 初始化相机
    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("SurfaceHolder is null");
        }
        if (cameraManager.isOpen()) {
            Log.e(TAG, "surfaceCreated: camera is open");
            return;
        }

        try {
            cameraManager.openDriver(surfaceHolder);
            if (handler == null) {
                handler = new CaptureActivityHandler(this, cameraManager, DecodeThread.ALL_MODE);
            }
            initCrop();
        } catch (IOException ioe) {
            Log.w(TAG, ioe);
            Utils.displayFrameworkBugMessageAndExit(this);
        } catch (RuntimeException e) {
            // Barcode Scanner has seen crashes in the wild of this variety:
            // java.lang.RuntimeException: Fail to connect to camera service
            Log.w(TAG, "Unexpected error initializing camera", e);
            Utils.displayFrameworkBugMessageAndExit(this);
        }
    }

    // 初始化截取的矩形区域
    private void initCrop() {
        // 获取相机的宽高
        int cameraWidth = cameraManager.getCameraResolution().y;
        int cameraHeight = cameraManager.getCameraResolution().x;

        // 获取布局中扫描框的位置信息
        int[] location = new int[2];
        scanCropView.getLocationInWindow(location);

        int cropLeft = location[0];
        int cropTop = location[1] - Utils.getStatusBarHeight(this);

        // 获取截取的宽高
        int cropWidth = scanCropView.getWidth();
        int cropHeight = scanCropView.getHeight();

        // 获取布局容器的宽高
        int containerWidth = scanContainer.getWidth();
        int containerHeight = scanContainer.getHeight();

        // 计算最终截取的矩形的左上角顶点x坐标
        int x = cropLeft * cameraWidth / containerWidth;
        // 计算最终截取的矩形的左上角顶点y坐标
        int y = cropTop * cameraHeight / containerHeight;

        // 计算最终截取的矩形的宽度
        int width = cropWidth * cameraWidth / containerWidth;
        // 计算最终截取的矩形的高度
        int height = cropHeight * cameraHeight / containerHeight;

        // 生成最终的截取的矩形
        mCropRect = new Rect(x, y, width + x, height + y);
    }

    @Override
    public Rect getCropRect() {
        return mCropRect;
    }

    @Override
    public Handler getHandler() {
        return handler;
    }

    @Override
    public CameraManager getCameraManager() {
        return cameraManager;
    }

    @Override
    public void handleDecode(Result result, Bundle bundle) {
        // 扫码成功之后回调的方法
        if (inactivityTimer != null) {
            inactivityTimer.onActivity();
        }
        // 播放蜂鸣声
        beepManager.playBeepSoundAndVibrate();

        Log.e("扫码结果====>", result.getText());
        pauseScan();
        payOrderByCode(result.getText());
    }

    private void payOrderByCode(String authCode) {
        Intent intent = new Intent();
        intent.putExtra(MainConfig.INTENT_CAPTURE_CODE, authCode);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 相册返回
        if (requestCode == CommonConfig.REQUESTCODE_CAPTURE_PICKER
                && resultCode == Activity.RESULT_OK && data != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Uri selectedImage = data.getData();
                    if (selectedImage != null && !TextUtils.isEmpty(selectedImage.getAuthority())) {
                        String filePath = AlbumUtil.getPath(CaptureActivity.this, selectedImage);
                        if (!TextUtils.isEmpty(filePath)) {
                            Result result = Utils.scanningImage(filePath);
                            showProgressDialog(result);
                        }
                    }
                }
            }).start();
        }
    }

    private void showProgressDialog(final Result result) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (result == null) {
                    ToastUtil.show("未发现二维码/条形码");
                } else {
                    pauseScan();
                    payOrderByCode(result.getText());
                }
            }
        });
    }

    @Override
    public void onPermissionDenied(List<String> permission) {
        if (permission != null && !permission.isEmpty()) {
            String perm = checkPermission(permission.toArray(new String[permission.size()]));
            boolean isFinish = true;
            if (TextUtils.equals(PermissionsConstant.WRITE_STORAGE, perm)) {
                isFinish = false;
            }
            if (perm != null) {
                ICommonProvider commonProvider = PublicProviderUtil.getProvider(ICommonProvider.class);
                if (commonProvider != null) {
                    commonProvider.openAppPermission(CaptureActivity.this, perm, isFinish);
                }
            }
        }
    }

    @Override
    public void onPermissionGranted(List<String> permissions) {
        super.onPermissionGranted(permissions);
        if (permissions != null) {
            if (TextUtils.equals(PermissionsConstant.CAMERA, permissions.get(0))) {
                isHasSurface = true;
                startScan();
            } else if (TextUtils.equals(PermissionsConstant.WRITE_STORAGE, permissions.get(0))) {
                AlbumUtil.openAlbum(CaptureActivity.this, CommonConfig.REQUESTCODE_CAPTURE_PICKER);
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (objectAnimator != null) {
            objectAnimator.end();
        }
        if (inactivityTimer != null) {
            inactivityTimer.shutdown();
        }
        super.onDestroy();
    }
}
